#!/bin/bash

acmeHome="/root/scripts/acme"
sslDir="${acmeHome}/.lego/certificates"
email="phiix@8z.net"
webroot="/home/wwwpub/pub"
certDir="/etc/nginx/cert"
expire=30
domain="$1"

function newSSL() {
    cd "${acmeHome}" || exit 1
    if ./lego -a -m "${email}" -d "${domain}" --http --http.webroot "${webroot}" run |grep -q "succeeded";then
        depSSL "${domain}.crt" "${domain}.key"
    fi
}

function renewSSL(){
    cd "${acmeHome}" || exit 1
    if ./lego -a -m "${email}" -d "${domain}" --http --http.webroot "${webroot}" renew --days ${expire} |grep -q "succeeded";then
        depSSL "${domain}.crt" "${domain}.key"
    fi
}

function depSSL(){
    cd "${sslDir}" || exit 1
    \cp -f "$1" "$2" "${certDir}" && systemctl force-reload nginx
}

function printHelp() {
    echo "Usage: $0 [domain] [new|renew]"
    exit 0
}

if [ $# -ge 2 ];then
    shift
    case $1 in
        new)
            newSSL
        ;;
        renew)
            renewSSL
        ;;
        *)
            printHelp
        ;;
    esac
else
    printHelp
fi
